package com.sajhasite.framework.tags;

import java.io.IOException;

import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import com.sajhasite.authentication.UserContext;

public class Greeting extends SimpleTagSupport {

	public void doTag() throws JspException, IOException {

		PageContext pageContext = (PageContext) getJspContext();
		HttpSession session = pageContext.getSession();

		UserContext userContext = null;

		if (session.getAttribute("user") != null) {
			userContext = (UserContext) session.getAttribute("user");
		}

		JspWriter out = getJspContext().getOut();
		String name = "";
		if (userContext == null) {
			out.println("<a href=\"/sajhasite/user/login.do\">Login</a>");

		} else if (!userContext.getUser().getDisplayName().isEmpty()) {
			name = getFirst10Char(userContext.getUser().getDisplayName());
			// out.println("Welcome "+userContext.getUser().getDisplayName());
		} else
			name = getFirst10Char(userContext.getUser().getEmail().split("@")[0]);
		// out.println("Welcome "+
		// userContext.getUser().getEmail().split("@")[0]);
		out.println("Welcome " + name);
	}

	private String getFirst10Char(String str) {

		if (str.length() < 10)
			return str;
		return str.substring(0, 10);

	}
}
